package services

import (
	"github.com/siaoynli/goProject/models"
)

//type AdminRegisterService struct {
//	UserName string `form:"username" json:"username" binding:"required,min=5,max=30"`
//	Password string `form:"password" json:"password" binding:"required,min=8,max=40"`
//}

type AdminRegisterService struct {
	UserName string `form:"username" json:"username" validate:"required,min=5,max=30"`
	Password string `form:"password" json:"password" validate:"required,min=5,max=30"`
	CsrfToken string `form:"csrf"`
}

func (service *AdminRegisterService) Valid() string {
	var count int
	models.DB.Model(&models.Admin{}).Where(&models.Admin{UserName: service.UserName}).Count(&count)
	if count > 0 {
		 return "用户名已经存在"
	}
	return ""
}

// 注册 用户登录函数
func (service *AdminRegisterService) Register() string {
	admin := models.Admin{}
	if str := service.Valid(); str != "" {
		return  str
	}
	if err := admin.SetPassword(service.Password); err != nil {
		return  "密码加密失败"
	}
	admin.UserName = service.UserName
	admin.Status = models.Inactive
	if err := models.DB.Create(&admin).Error; err != nil {
		return  "创建管理员失败"
	}
	return  ""
}
